package com.blog.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.blog.dao.dos.Archives;
import com.blog.blog.dao.mapper.*;
import com.blog.blog.dao.pojo.*;
import com.blog.blog.service.*;
import com.blog.blog.utils.UserThreadLocal;
import com.blog.blog.vo.ArticleBodyVo;
import com.blog.blog.vo.ArticleVo;
import com.blog.blog.vo.Result;
import com.blog.blog.vo.TagVo;
import com.blog.blog.vo.params.ArticleParam;
import com.blog.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    TagService tagService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    ArchivesMapper archivesMapper;
    @Autowired
    ArticleBodyMapper articleBodyMapper;
    @Autowired
    CategoryServiceImpl categoryService;
    @Autowired
    ThreadService threadService;
    @Autowired
    ArticleTagMapper articleTagMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CommentsMapper commentsMapper;
    /**
     * 分页查询数据库article表
     * @param pageParams
     * @return
     */
    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(page,
                pageParams.getCategoryId(), pageParams.getTagId(), pageParams.getYear(), pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        if (!records.isEmpty()) {
            for (Article record : records) {
                LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Comment::getArticleId,record.getId());
                Long count = commentsMapper.selectCount(queryWrapper);
                record.setCommentCounts(count.intValue());
            }
        }
        return Result.success(copyList(records,true,true));
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        ArrayList<ArticleVo> articleVoArrayList = new ArrayList<>();
        for (Article record : records) {
            articleVoArrayList.add(copy(record, isTag, isAuthor,false,false));
        }
        return articleVoArrayList;
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory) {
        ArrayList<ArticleVo> articleVoArrayList = new ArrayList<>();
        for (Article record : records) {
            articleVoArrayList.add(copy(record, isTag, isAuthor, isBody, isAuthor));
        }
        return articleVoArrayList;
    }

    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody,boolean isCategory ) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        if (article.getCreateDate() != null) {
            articleVo.setCreateDate(article.getCreateDate().toString());
        }//并不是所有接口 都需要标签 作者信息
        if (isTag) {
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(this.findArticleBodyById(article.getBodyId()));
        }
        if (isCategory) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(article.getCategoryId()));
        }
        return articleVo;
    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Article::getViewCounts);
        wrapper.select(Article::getId,Article::getTitle);
        wrapper.last("limit " + limit);
        //select id,title from Article order by view_counts desc limit 5
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(copyList(articles,false,false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Article::getCreateDate);
        wrapper.select(Article::getId,Article::getTitle);
        wrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result listArchives() {
        SysUser sysUser = UserThreadLocal.get();
        List<Archives> archivesList = archivesMapper.listArchives(sysUser.getId().toString());
        return Result.success(archivesList);
    }

    @Override
    public ArticleVo findArticleById(Long id) {
        /**
         * 根据id查询文章信息
         * 根据bodyId和categoryId关联查询
         */
        Article article = articleMapper.selectById(id);
        //查看完文章，新增阅读数
        //查看完文章后，本应该直接返回数据了，这时候做了一个更新操作，更新时加写锁，阻塞其它的读操作，性能就会比较低
        //更新增加了此次接口的耗时，如果一旦更新出现问题，不能影响查看文章的操作
        /**
         * 线程池  可以把更新操作扔到线程池中去执行，和主线程就不相关了
         */
        threadService.updateViewCount(articleMapper,article);
        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getArticleId,id);
        Long count = commentsMapper.selectCount(lambdaQueryWrapper);
        article.setCommentCounts(count.intValue());
        return copy(article,true,true,true,true);
    }

    public ArticleBodyVo findArticleBodyById(Long articleId) {
        QueryWrapper<ArticleBody> wrapper = new QueryWrapper<>();
        wrapper.eq("id", articleId);
        ArticleBody articleBody = articleBodyMapper.selectOne(wrapper);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        //此接口要加入到登录拦截器当中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1. 发布文章 目的 构建Article对象
         * 2. 作者id 当前的登录用户
         * 3. 标签 要将标签加入到关联列表当中
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setCategoryId(articleParam.getCategory().getId());
        article.setCreateDate(new Timestamp(System.currentTimeMillis()));
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setBodyId(-1L);
        //插入之后会生成一个文章id
        this.articleMapper.insert(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                //如果redis中没有，则说明为新增标签
                String t = stringRedisTemplate.opsForValue().get(sysUser.getId() + "_" + tag.getTagName());
                if (t == null) {
                    //存入mysql
                    Tag newTag = new Tag();
                    newTag.setTagName(tag.getTagName());
                    newTag.setUserId(sysUser.getId());
                    tagMapper.insert(newTag);
                    //存入redis
                    stringRedisTemplate.opsForValue().set(sysUser.getId() + "_" +tag.getTagName(), newTag.getId().toString());
                    articleTag.setTagId(newTag.getId());
                } else {
                    articleTag.setTagId(Long.parseLong(t));
                }
                this.articleTagMapper.insert(articleTag);
            }
        }
        //articlebody
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBody.setArticleId(article.getId());
        articleBodyMapper.insert(articleBody);
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(article.getId());
        return Result.success(articleVo);
    }

    @Override
    public List<JSONObject> findAllPersonalArticle() {
        SysUser sysUser = UserThreadLocal.get();
        LambdaQueryWrapper<Article> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Article::getAuthorId, sysUser.getId())
                .orderByDesc(Article::getCreateDate);
        List<Article> articles = articleMapper.selectList(lambdaQueryWrapper);
        ArrayList<JSONObject> list = new ArrayList<>();
        if (!articles.isEmpty()) {
            for (Article article : articles) {
                JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
                jsonObject.put("id", JSON.toJSONString(article.getId()));
                jsonObject.put("title", article.getTitle());
                jsonObject.put("summary", article.getSummary());
                LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Comment::getArticleId,article.getId());
                Long count = commentsMapper.selectCount(queryWrapper);
                jsonObject.put("commentCounts", count);
                jsonObject.put("viewCounts", article.getViewCounts());
                jsonObject.put("author", sysUserMapper.selectById(article.getAuthorId()).getNickname());
                jsonObject.put("bodyId", article.getBodyId());
                jsonObject.put("categoryId", article.getCategoryId());
                jsonObject.put("weight", article.getWeight());
                jsonObject.put("createDate", article.getCreateDate());
                list.add(jsonObject);
            }
        }
        return list;
    }

    @Transactional
    @Override
    public void delArticleById(Long articleId) {
        //删除ArticleBody表中相关数据
        LambdaQueryWrapper<ArticleBody> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ArticleBody::getArticleId, articleId);
        articleBodyMapper.delete(lambdaQueryWrapper);
        //删除ArticleTag表中相关数据
        LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(ArticleTag::getArticleId, articleId);
        articleTagMapper.delete(lambdaQueryWrapper1);
        //删除Article表中相关数据
        articleMapper.deleteById(articleId);
        //删除comment表中数据
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getArticleId,articleId);
        commentsMapper.delete(commentLambdaQueryWrapper);
    }

}
